package com.example.demo.service.face.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.constant.FaceResConstant;
import com.example.demo.pojo.mgdjson.FaceResPO;
import com.example.demo.service.face.IFaceRegService;
import com.example.demo.util.DateUtil;
import com.example.demo.util.RestRequestUtil;
import com.example.demo.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 人脸识别service
 * @author: liyuan
 * @data 2020-11-27 11:40
 */
@Service
public class FaceRegServiceImpl implements IFaceRegService {

    @Autowired
    private MongoTemplate mongoTemplate;
    private static Logger logger = LoggerFactory.getLogger(FaceRegServiceImpl.class);
    @Value("${banji.path}")
    private String banjiPath;
    @Value("${pythonMain.path}")
    private String pythonMainPath;
    @Value("${python.v}")
    private String pythonV;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public ResultVO recognizie(String picture) throws IOException, InterruptedException {
        //存到表中、
        FaceResPO faceResPO = new FaceResPO();
        String face_id = DateUtil.date2Str(new Date(), DateUtil.YMD_HMS);
        faceResPO.set_id(face_id);
        faceResPO.setFilePath(picture);
        faceResPO.setCreateTime(new Date());
        faceResPO.setStatus((byte) FaceResConstant.NO_RRG);
        mongoTemplate.insert(faceResPO);
        //人脸识别
//        String s = FaceRegUtil.detectOne(pythonV, picture, pythonMainPath, banjiPath);
        String s = dJangoRestServer(picture);
        if (StringUtils.isEmpty(s)) {
            return ResultVO.error();
        }
        //更新表
        Update update = new Update();
        update.set("number", s);
        update.set("updateTime", new Date());
        update.set("status", FaceResConstant.RRGED);
        mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(face_id)), update, FaceResPO.class);
        //查询返回
        FaceResPO resPO = mongoTemplate.findById(face_id, FaceResPO.class);
        return new ResultVO(1000, JSONObject.toJSON(resPO));
    }

    private String dJangoRestServer(String picture) {
        HttpHeaders header = RestRequestUtil.getHeader(MediaType.MULTIPART_FORM_DATA);
        //上传文件
        FileSystemResource resource = new FileSystemResource(new File(picture));
        MultiValueMap<String, Object> multiValueMap = RestRequestUtil.getEntityByMultiForm();
        multiValueMap.add("picture", resource);
        HttpEntity entity = RestRequestUtil.getEntity(multiValueMap, header);
        return restTemplate.postForObject("http://139.155.226.4:8000/faceReg", entity, String.class);
    }

    /***
     * 将图片路径写到表中
     * 调用人脸识别算法，返回一个字符串；或者搭建消息队列服务器
     * 取出、修改表中的信息，返回识别结果信息
     * @param picture
     * @return
     */
    public ResultVO recognizieOld(String picture) {
        //存到表中、
        FaceResPO faceResPO = new FaceResPO();
        faceResPO.set_id(DateUtil.date2Str(new Date(), DateUtil.YMD_HMS));
        faceResPO.setFilePath(picture);
        faceResPO.setCreateTime(new Date());
        faceResPO.setStatus((byte) FaceResConstant.NO_RRG);
        mongoTemplate.insert(faceResPO);
        //取出
        Criteria criteria = Criteria.where("status").is(FaceResConstant.NO_RRG);
        Query query = Query.query(criteria).limit(FaceResConstant.LIMIT);
        List<FaceResPO> faceResPOS = mongoTemplate.find(query, FaceResPO.class);
        logger.info("读取结果：{}", faceResPOS.toString());
        //人脸识别块

        //修改
        List<FaceResPO> resPOS = new ArrayList<>(faceResPOS.size());
        Update update = new Update();
        for (FaceResPO po : faceResPOS) {
            String number = po.getFilePath();
            po.setNumber("2111703338");
            update.set("number", po.getNumber());
            update.set("updateTime", new Date());
            update.set("status", FaceResConstant.RRGED);
//            update.currentDate("updateTime");
            //一条条更新
            mongoTemplate.updateFirst(Query.query(Criteria.where("filePath").is(po.getFilePath())), update, FaceResPO.class);
            resPOS.add(po);
        }
        //用着不习惯，
        criteria = Criteria.where("status").in(FaceResConstant.NO_RRG, FaceResConstant.RRGED, null);
        List<FaceResPO> upPOS = mongoTemplate.find(Query.query(criteria), FaceResPO.class);
        logger.info("读取结果：{}", upPOS.toString());
        //需要改写
        return new ResultVO<>(1000, resPOS);
    }
}
